package com.jxd.project.travel.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jxd.project.travel.dao.IDictTypeDao;
import com.jxd.project.travel.model.DictType;
import com.jxd.project.travel.service.IDictTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @ClassName DictTypeImpl
 * @Description TODO
 * @Author 邢子剑
 * @Date 2025/10/9 下午5:33
 * @Version 1.0
 */
@Service
public class DictTypeImpl extends ServiceImpl<IDictTypeDao, DictType> implements IDictTypeService{
    @Autowired
    private IDictTypeDao dictTypeDao;


    @Override
    public IPage<DictType> getAll(Page<DictType> page, String type) {
        LambdaQueryWrapper<DictType> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(DictType::getType, type);
        return dictTypeDao.selectPage(page, queryWrapper);
    }

    @Override
    @Transactional
    public boolean deleteType(int id) {
//        DictType dictType = dictTypeDao.selectById(id);
//        if (dictType == null) {
//            throw new RuntimeException("字典类型不存在");
//        String typeName = dictType.getType(); // 假设类型名称是关联字典项的字段
//        // 2. 先删除该类型下的所有字典项（关键步骤）
//        int itemDeleteCount = dictTypeDao.deleteByType(typeName); // 按类型名称删除字典项
//        // 3. 再删除字典类型本身
//        int typeDeleteCount = dictTypeDao.deleteById(id);
//        // 4. 返回删除结果（确保两者都删除成功）
//        return typeDeleteCount > 0 && itemDeleteCount >= 0;
        DictType dictType = dictTypeDao.selectById(id);
        if (dictType == null) {
            throw new RuntimeException("字典类型不存在或已被删除");
        }
        // 逻辑删除字典项（按类型）
        QueryWrapper<DictType> itemWrapper = new QueryWrapper<>();
        itemWrapper.eq("type", dictType.getType());
        this.remove(itemWrapper);

        // 逻辑删除字典类型
        return this.removeById(id);
    }

    @Override
    public boolean checkDictionaryTypeExists(String type) {
        LambdaQueryWrapper<DictType> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DictType::getType, type);
        return dictTypeDao.selectOne(queryWrapper) != null;
    }
}
